package com.cy.mall.service.fujue.impl;

import com.cy.mall.comm.constant.Constants;
import com.cy.mall.comm.utils.CommonUtils;
import com.cy.mall.comm.utils.JsonObjectMapper;
import com.cy.mall.comm.utils.RSAUtils;
import com.cy.mall.dao.mapper.order.OrderGoodsExtraInfoMapper;
import com.cy.mall.model.Result;
import com.cy.mall.model.dto.fujue.resp.LoanDataDTO;
import com.cy.mall.model.dto.fujue.resp.NotifyDataDTO;
import com.cy.mall.model.enums.MessageType;
import com.cy.mall.model.enums.ThirdSource;
import com.cy.mall.model.enums.order.OrderFinalStatusE;
import com.cy.mall.service.BaseService;
import com.cy.mall.service.fujue.FujueApiService;
import com.cy.mall.service.fujue.FujueJobService;
import com.cy.mall.service.message.MessageService;
import com.cy.mall.service.order.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description 富爵（云科贷）的定时任务service
 * @Author tanyilin
 * @Date 2019/4/8 14:21
 */
@Slf4j
@Service
public class FujueJobServiceImpl extends BaseService implements FujueJobService {

    @Autowired
    private OrderGoodsExtraInfoMapper orderGoodsExtraInfoMapper;
    @Autowired
    private FujueApiService fujueApiService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MessageService messageService;


    @Override
    public void queryLoanDataBatch() {
        //先查询所有云科贷产品[嘻唰唰、薪想事成]的订单号 thirdLoanId
        List<Long> productIdList = new ArrayList<>();
        productIdList.add(Constants.XSS_PRODUCTID);
        productIdList.add(Constants.XXSC_PRODUCTID);
        List<String> thirdStatusList = new ArrayList<>();
        thirdStatusList.add("1");
        thirdStatusList.add("2");
        thirdStatusList.add("3");
        thirdStatusList.add("5");
        //查询需要查询的 loanId
        List<String> thirdLoanIdList = orderGoodsExtraInfoMapper.selectYunKeDaiLoanIdList(productIdList, thirdStatusList);
        if(CommonUtils.isEmpty(thirdLoanIdList)) {
            log.info("定时任务--需要请求云科查询贷款数据的订单数据有 [0] 条");
            return;
        }
        //循环查询云科接口
        log.info("定时任务--需要请求云科查询贷款数据的订单数据有 [{}] 条", thirdLoanIdList.size());
        for(String loanId : thirdLoanIdList) {
            log.info("定时任务--查询云科订单贷款数据，loanId = {}", loanId);
            //请求云科查询接口
            Result<Map<String, Object>> result = fujueApiService.queryLoanData(loanId);
            if(!result.isOk()) {
                continue;
            }
            //解密查询返回数据
            Map<String, Object> paramMap = result.getData();
            String encryptData = String.valueOf(paramMap.get("data"));
            log.info("定时任务--获取贷款数据 api，返回参数data密文：{}", encryptData);
            String decryptData = RSAUtils.privateDecrypt(encryptData, Constants.FUJUE_RSA_PRIVATE_KEY);
            log.info("定时任务--获取贷款数据 api，返回参数data明文：{}", decryptData);
            //解析明文data
            LoanDataDTO loanData = JsonObjectMapper.read(decryptData, LoanDataDTO.class);
            if("0000".equals(loanData.getRtCode())) {
                //保存更新贷款数据
                Result saveResult =  orderService.saveLoanData(loanData, ThirdSource.YUNKEDAI);
                if(saveResult.isOk()) {
                    OrderFinalStatusE finalStatus = (OrderFinalStatusE) saveResult.getData();
                    switch (finalStatus) {
                        case DECISION_PASS: //云科通知 审批通过，即马先生显示为 '授信审批`通过'
                            // 微信发送通知
                            messageService.sendMessage(loanData.getLoanId(), MessageType.ORDER_DECISION_PASS);
                            break;

                        case DECISION_REJECT: //云科通知 审批拒绝，即马先生显示为 '授信审批拒绝'
                            // 微信发送通知
                            messageService.sendMessage(loanData.getLoanId(), MessageType.ORDER_DECISION_REJECT);
                            break;

                        case LOAN_SUCCESS: //云科通知 放款成功
                            // 微信发送通知
                            messageService.sendMessage(loanData.getLoanId(), MessageType.ORDER_LOAN_SUCCESS);
                            break;

                        default:
                            break;
                    }
                }
            }


        }

    }

    @Override
    public void getJydOrderDataBatch(List<String> thirdStatusList) {
        //先查询所有云科贷产品[家易贷]的订单号 thirdLoanId
        List<Long> productIdList = new ArrayList<>();
        productIdList.add(Constants.JYD_PRODUCTID);
        //查询需要查询的 loanId
        List<String> thirdLoanIdList = orderGoodsExtraInfoMapper.selectYunKeDaiLoanIdList(productIdList, thirdStatusList);
        if(CommonUtils.isEmpty(thirdLoanIdList)) {
            log.info("定时任务--需要请求云科查询订单数据的订单数据共有 [0] 条");
            return;
        }
        //循环查询云科接口
        log.info("定时任务--需要请求云科查询订单数据的订单数据共有 [{}] 条", thirdLoanIdList.size());
        for(String loanId : thirdLoanIdList) {
            log.info("定时任务--查询云科订单数据，loanId = {}", loanId);
            //请求云科查询接口
            Result<Map<String, Object>> result = fujueApiService.getOrderInfo(loanId);
            if(!result.isOk()) {
                continue;
            }
            //解密查询返回数据
            Map<String, Object> paramMap = result.getData();
            String encryptData = String.valueOf(paramMap.get("data"));
            log.info("定时任务--查询云科订单数据 api，返回参数data密文：{}", encryptData);
            String decryptData = RSAUtils.privateDecrypt(encryptData, Constants.FUJUE_RSA_PRIVATE_KEY);
            log.info("定时任务--查询云科订单数据 api，返回参数data明文：{}", decryptData);
            //解析明文data
            NotifyDataDTO notifyData = JsonObjectMapper.read(decryptData, NotifyDataDTO.class);
            log.info("Json -----------> javaBean [NotifyDataDTO] = {}", notifyData);

            //更新订单数据
            Result updateResult = orderService.doUpdateOrderData(notifyData);
            //发送微信消息通知
            if(updateResult.isOk()) {
                OrderFinalStatusE finalStatus = (OrderFinalStatusE) updateResult.getData();
                switch (finalStatus) {
                    case ADMISSION_PASS:
                        //'准入额度通过'， 微信发送通知
                        messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_ADMISSION_PASS);
                        break;
                    case ADMISSION_REJECT:
                        //'准入额度拒绝'， 微信发送通知
                        messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_ADMISSION_REJECT);
                        break;
                    case SIGN_WAIT:
                        //'资料审核通过-去签约'，微信发送通知
                        messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_MATERIAL_AUDIT_PASS);
                        break;
                    case MATERIAL_AUDIT_REJECT:
                        //'资料审核拒绝'，微信发送通知
                        messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_MATERIAL_AUDIT_REJECT);
                        break;
                    case LOAN_SUCCESS:
                        //'放款成功'，微信发送通知
                        messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_LOAN_SUCCESS);
                        break;
                    case REPAYING:
                        //'放款成功-还款中'，微信发送通知
                        messageService.sendMessage(notifyData.getLoanId(), MessageType.ORDER_LOAN_SUCCESS);
                        break;
                    default:
                        break;
                }
            }

        }
    }




}
